Ext.define('DragonApp.view.white.Controller', {
    extend: 'DragonApp.view.foundation.ViewController',

    alias: 'controller.whitelist',

    config: {
        severlist: Ext.create('DragonApp.store.JsonPServer', {})
    },

    //新增Account

    onAddAccount: function(button, e, options) {
        var xtype = 'accountform';
        var title = '新增名单';
        this.createDialog(xtype, title);
    },

    //新增IP段

    onAddIp: function(button, e, options) {
        var xtype = 'ipform';
        var title = '新增名单';
        this.createDialog(xtype, title);
    },

    //触发弹窗

    createDialog: function(xtype, title) {
        var me = this,
            view = me.getView();

        me.dialog = view.add({
            xtype: xtype,
            title: title
        });
        me.dialog.show();
    },

    //编辑白名单

    onEdit: function(button) {
        this.createEditDialog(button.getWidgetRecord());
    },

    //白名单编辑

    createEditDialog: function(record) {

        var me = this,
            view = me.getView();

        var data = record.getData();
        var type = data.type;

        var xtype = ("ip" == type) ? 'ipform' : 'accountform';
        me.dialog = view.add({
            xtype: xtype,
            title: '编辑名单'
        });
        if (!Ext.isEmpty(record)) {
            me.dialog.down("form").loadRecord(record);
        }

        var serverField = Ext.ComponentQuery.query(xtype + ' multiservercombo')[0];
        serverField.on('beforequery', function() {
            return false;
        });
        serverField.setReadOnly(true);
        me.dialog.show();
    },

    //取消新增或编辑
    onCancel: function(button, e, options) {
        var me = this;
        var window = button.up('window');

        Ext.destroy(window);
    },

    //获取数据仓库
    getStore: function(component) {

        var className = Ext.getClassName(Ext.getClass(component));
        var store;
        if (className.search(/Account/) >= 0) {
            store = Ext.data.StoreManager.lookup('jsonPWhiteAccountStore');
        } else if (className.search(/IP/) >= 0) {
            store = Ext.data.StoreManager.lookup('jsonPWhiteIpStore');
        }

        return store;
    },

    //保存新增或编辑
    onSave: function(button, e, options) {

        var window = button.up('window');
        var store = this.getStore(window);

        var form = window.down('form').getForm();
        if (!form.isValid()) {
            return;
        }
        var formValue = form.getValues();
        formValue.server = formValue.server.toString();

        var url;
        //添加、编辑
        if (Ext.isEmpty(formValue.id)) {

            url = DragonApp.ux.config.Config.getUrl('/index/White/add/');
        } else {
            url = DragonApp.ux.config.Config.getUrl('/index/White/update/');
        }

        window.mask('请稍候...');

        Ext.data.JsonP.request({
            url: url,
            async: false,
            params: formValue,
            callbackKey: "callback",
            success: function(result) {

                window.unmask();
                DragonApp.util.Msg.showToast(result.msg);

                switch (result.success) {
                    case true:
                        form.destroy();
                        window.destroy();
                        store.load();
                        break;

                    case false:
                        form.destroy();
                        window.destroy();
                        break;
                }
            },
            failure: function(result) {
                window.unmask();
                DragonApp.util.Msg.showToast(result);
            }
        });
    },

    //单记录删除
    onDelete: function(button, e, options) {

        //当前记录

        var record = button.getWidgetRecord();
        var param = { id: record.get('id') };
        var url = DragonApp.ux.config.Config.getUrl('/index/White/delete/');

        //删除请求

        this.deletePrompt(url, param, record);

    },

    //获取多选ID
    getSelectedRecordId: function(records) {

        var selected = [];
        records.forEach(function(item) {
            var data = item.getData();
            selected.push(data.id);
        });
        return selected;
    },

    //多条记录删除
    onBatDelete: function(button, e, options) {

        var grid = this.getView();
        var store = grid.getStore();

        var records = grid.getSelectionModel().getSelection();

        //批量获取ID
        var arr = [];

        records.forEach(function(item) {
            arr.push(item.id);
        });

        //获取序号
        var param = {};
        param.id = JSON.stringify(arr);

        var url = DragonApp.ux.config.Config.getUrl('/index/White/batDelete/');

        this.batDeletePrompt(url, param, records, store);

    },

    //回车搜索
    onTextFieldSpecialKeySearch: function(field, e, options) {
        if (e.getKey() === e.ENTER) {
            if ('searchfield_account' == field.itemId) {
                this.onAccountSearch();
            } else if ('searchfield_ip' == field.itemId) {
                this.onIPSearch();
            }
        }
    },
    //账号筛选
    onAccountSearch: function(button, e, options) {

        //搜索字段
        var searchFilter = Ext.ComponentQuery.query('whitebar_account')[0];
        var searchField = searchFilter.queryById('searchfield_account');

        //仓库复位
        var store = Ext.data.StoreManager.lookup('jsonPWhiteAccountStore');
        store.clearFilter();

        //仓库过滤
        store.filterBy(function(item) {
            if ('account' == item.get('type')) {
                return (item.get('account').indexOf(searchField.getValue()) >= 0);
            } else {
                return false;
            }
        });
    },
    //IP筛选
    onIPSearch: function(button, e, options) {

        //搜索字段
        var searchFilter = Ext.ComponentQuery.query('whitebar_ip')[0];
        var searchField = searchFilter.queryById('searchfield_ip');

        //仓库过滤
        var store = Ext.data.StoreManager.lookup('jsonPWhiteIpStore');
        store.clearFilter();

        //仓库过滤
        store.filterBy(function(item) {
            if ('ip' == item.get('type')) {
                var contentfilter = (item.get('ip_from').indexOf(searchField.getValue()) >= 0 || item.get('ip_end').indexOf(searchField.getValue()) >= 0);
                return (contentfilter);
            } else {
                return false;
            }
        });
    },
    //===========
    //服务器渲染
    //===========
    serverRender: function(value) {

        var store = this.getSeverlist();

        for (var i = 0; i < store.getCount(); i++) {

            var record = store.getAt(i);
            if (value == record.get('id')) {
                return record.get('hostname');
            }
        }
        return value;
    }
});